package com.cff.springbootwork.websocket.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.BinaryMessage;

import com.cff.springbootwork.websocket.dto.ResultModel;
import com.cff.springbootwork.websocket.handler.WebSocketHandler;
import com.cff.springbootwork.websocket.memory.WebSocketUser;

@RestController
@RequestMapping("/im")
public class WebSocketController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private WebSocketHandler websocketHandler;

	@RequestMapping(value = "/fileUpload")
	public ResultModel fileUpload(@RequestParam("userName") String userName, @RequestParam MultipartFile[] myfiles,
			HttpServletRequest request) {
		logger.info("收到发往用户[{}]的文件上传请求;文件数量:{}", userName, myfiles.length);

		int count = 0;
		for (MultipartFile myfile : myfiles) {
			if (myfile.isEmpty()) {
				count++;
			}
			logger.info("文件原名:{};文件类型:", myfile.getOriginalFilename(), myfile.getContentType());
			try (ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
					InputStream is = myfile.getInputStream();) {
				byte[] buff = new byte[100]; // buff用于存放循环读取的临时数据
				int rc = 0;
				while ((rc = is.read(buff, 0, 100)) > 0) {
					swapStream.write(buff, 0, rc);
				}
				byte[] in_b = swapStream.toByteArray(); // in_b为转换之后的结果
				logger.info("正在发送文件: ");
				websocketHandler.sendMessageToUser(userName, new BinaryMessage(in_b));
			} catch (IOException e) {
				logger.error("文件原名:{}", myfile.getOriginalFilename(), e);
				e.printStackTrace();
				count++;
				continue;
			}
		}
		return ResultModel.ok(count);
	}

	@RequestMapping(value = "/setUser")
	public ResultModel setUser(@RequestParam("userName") String userName, HttpServletRequest request) {
		logger.info("设置用户[{}]", userName);

		request.getSession().setAttribute("userName", userName);
		return ResultModel.ok();
	}
	
	@RequestMapping(value = "/user")
	public ResultModel user(HttpServletRequest request) {
		Object userName = request.getSession().getAttribute("userName");
		if(userName == null)return ResultModel.error("无用户");
		return ResultModel.ok(userName);
	}
	
	@RequestMapping(value = "/userList")
	public ResultModel userList() {
		return ResultModel.ok(WebSocketUser.getUserList());
	}
}
